package com.qf.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.pojo.respVo.BaseResp;
import com.qf.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyFilter extends ZuulFilter {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    JwtUtils jwtUtils;

    private final List URLlist = new ArrayList<>();

    /**
     * 过滤器的类型
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器的执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER;
    }

    /**
     * 是否进行拦截
     * @return
     */
    @Override
    public boolean shouldFilter() {

        //获取到全局的请求路径
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取到当前的请求
        HttpServletRequest request = currentContext.getRequest();
        //放行或者拦截请求
        String requestURI = request.getRequestURI();
        if (URLlist.contains(requestURI)){
            return false;
        }
        return true;
    }

    /**
     * 拦截后执行的方法
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //需要进行认证处理
        //1.从request请求中获取cookie
        //获取到全局的请求路径
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取到当前的请求
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        Cookie[] cookies = request.getCookies();
        if (cookies==null||cookies.length==0){
            writeResponse(response,new BaseResp(0,"用户未登录！",null,null));
            //停止i请求继续向后执行
            currentContext.setSendZuulResponse(false);
        }else {
            String token = null;
            for (Cookie cook : cookies
            ) {
                if (cook.getName().equals("token")) {
                    token = cook.getValue();
                }
            }
            if (token == null || token.trim().isEmpty()) {
                writeResponse(response, new BaseResp(0, "用户未登录！", null, null));
                currentContext.setSendZuulResponse(false);
            } else {
                //从redis中获取到Token值
                Boolean aBoolean = redisTemplate.hasKey(token);
                if (!aBoolean) {
                    writeResponse(response, new BaseResp(0, "登录失效请重新登录！", null, null));
                    currentContext.setSendZuulResponse(false);
                } else {
                    Object o = redisTemplate.opsForValue().get(token);
                    Integer verfiy = jwtUtils.verfiy(o.toString());
                    if (verfiy == 0) {
                        writeResponse(response, new BaseResp(0, "token失效！", null, null));
                        currentContext.setSendZuulResponse(false);
                    } else {
                        //如果认证通过，则需要延长改key的时长
                        redisTemplate.expire(token, 30, TimeUnit.MINUTES);
                    }
                }
            }
        }
        return null;
    }
    public static void writeResponse(HttpServletResponse response, BaseResp baseResp){
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            String o = JSONObject.toJSONString(baseResp);
            writer.write(o);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.flush();
            writer.close();
        }


    }


    @PostConstruct
    public void addURl(){
        URLlist.add("/qflive-user/user/login");
        URLlist.add("/qflive-user/user/registry");
        URLlist.add("/qflive-user/user/getCode");
        URLlist.add("/qflive-user/user/validataEmail");
        URLlist.add("/qflive-user/user/validataloginName");
        URLlist.add("/qflive-user/user/findUserByToken");
        URLlist.add("/qflive-pay/pay/callback");
    }
}
